<template>
  <el-cascader
    v-model="select"
    v-bind="$attrs"
    v-on="$listeners"
    v-loading="loading"
    element-loading-spinner="el-icon-loading"
    :options="customerType"
    :props="props"
    @change="handleChange"
  ></el-cascader>
</template>

<script>
export default {
  components: {},
  props: {
    value: String,
    isGua: {
      type: Boolean,
      default: false,
    },
  },
  model: {
    prop: 'value',
    event: 'select',
  },
  data() {
    return {
      loading: false,
      select: '',
      props: {
        label: 'label',
        value: 'value',
      },
    }
  },
  computed: {
    isUnion() {
      return this.$store.getters.user?.scopeArr?.includes('dirGuaPro') ?? false
    },
    orgList() {
      return this.$store.getters.enumOrgClass
    },
    initObject() {
      return this.orgList.reduce((a, item) => {
        a[item.orgClass] = {
          value: +item.customerType === 2 ? ['person', item.orgClass] : ['com', item.orgClass],
          item: item,
        }
        return a
      }, {})
    },
    customerType() {
      const orgList =
        this.isUnion || this.isGua ? this.orgList.filter(item => +item.busType !== 2) : this.orgList
      return [
        {
          label: '个人',
          value: 'person',
          children: orgList
            .filter(item => +item.customerType === 2)
            .map(item => {
              return {
                label: item.orgClassName,
                value: item.orgClass,
                customer_type: 2,
                busType: item.busType,
              }
            }),
        },
        {
          label: '法人',
          value: 'com',
          children: orgList
            .filter(item => +item.customerType === 1)
            .map(item => {
              return {
                label: item.orgClassName,
                value: item.orgClass,
                customer_type: 1,
                busType: item.busType,
              }
            }),
        },
      ]
    },
  },
  watch: {
    value(val) {
      if (val !== this.select) {
        this.initSelect(val)
      }
    },
  },
  created() {
    this.$store.dispatch('getEnumOrgClass').then(() => {
      this.initSelect(this.value)
    })
  },
  mounted() {},
  methods: {
    initSelect(val) {
      const data = this.initObject[val] || {}
      this.select = data.value || []
    },
    handleChange(val) {
      const select = Array.isArray(val) && val.length ? val[val.length - 1] : '' || ''
      const data = this.initObject[select] || {}
      this.select = select
      this.$emit('select', select, data.item || null)
    },
  },
}
</script>

<style lang="scss" scoped></style>
